package axdoc.rule.handle;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import axdoc.dao.CommonActivityDao;
import axdoc.model.CommonActivity;
import axdoc.rule.MessageHandle;
import axdoc.rule.check.AbsCheck;
import axdoc.rule.check.LoadChecksUtil;
import axdoc.util.StringUtils;

public class CommonActivityHandle implements MessageHandle {

	private static Logger logger = LoggerFactory.getLogger(CommonActivityHandle.class);

	CommonActivityDao commonActivityDao;

	public CommonActivityDao getCommonActivityDao() {
		return commonActivityDao;
	}

	public void setCommonActivityDao(CommonActivityDao commonActivityDao) {
		this.commonActivityDao = commonActivityDao;
	}

	@Override
	public void handle(JSONObject json) {
		logger.info("接收处理消息 | " + json);
		boolean flag = false;
		Integer type = json.getInteger("type");
		List<CommonActivity> acts = commonActivityDao.queryByEventType(type);
		if (acts != null && acts.size() > 0) {
			for (CommonActivity act : acts) {
				String rules = act.getRules();
				logger.info("接收处理消息 ^ 规则 ^ " + rules);
				if (StringUtils.isNotBlank(rules)) {
					List<AbsCheck> checks = LoadChecksUtil.initCheck(JSONArray.parseArray(rules));
					for (AbsCheck check : checks) {
						if (check.check(json)) {
							flag = true;
						} else {
							flag = false;
							break;
						}
					}
				}
				if (flag) {
					String dones = act.getDones();
					logger.info("接收处理消息 ^ 行为 ^ " + dones);
				}
			}
		}
	}

}
